// 本地通知闹钟管理器
class LocalNotificationManager {
	
	// 创建本地通知闹钟
	createLocalNotification(alarm) {
		// #ifdef APP-PLUS
		try {
			// 计算通知时间
			const notificationTime = this.calculateNotificationTime(alarm);
			
			if (!notificationTime) {
				console.error('无法计算通知时间');
				return false;
			}
			
			// 创建本地通知
			plus.push.createMessage(
				`${alarm.time} - ${alarm.label}`,
				'',
				{
					title: '⏰ 闹钟提醒',
					when: notificationTime,
					cover: false,
					sound: 'system',
					vibrate: alarm.vibrate ? [1000, 1000, 1000, 1000, 1000] : undefined,
					lights: true,
					priority: 1, // 高优先级
					category: 'alarm',
					ongoing: false,
					autoCancel: true,
					extra: {
						alarmId: alarm.id,
						alarmTime: alarm.time,
						alarmLabel: alarm.label,
						vibrate: alarm.vibrate
					}
				}
			);
			
			console.log(`本地通知已创建: ${alarm.time} - ${alarm.label}`);
			console.log(`通知时间: ${notificationTime}`);
			
			return true;
			
		} catch (error) {
			console.error('创建本地通知失败:', error);
			return false;
		}
		// #endif
		
		// #ifndef APP-PLUS
		console.log('非APP环境，无法创建本地通知');
		return false;
		// #endif
	}
	
	// 计算通知时间
	calculateNotificationTime(alarm) {
		const now = new Date();
		const [hours, minutes] = alarm.time.split(':').map(Number);
		
		if (alarm.type === 'once' && alarm.date) {
			// 一次性闹钟
			const alarmDateTime = new Date(alarm.date);
			alarmDateTime.setHours(hours, minutes, 0, 0);
			
			if (alarmDateTime > now) {
				return alarmDateTime;
			} else {
				console.warn('一次性闹钟时间已过');
				return null;
			}
		} else if (alarm.type === 'repeat' && alarm.repeatDays && alarm.repeatDays.length > 0) {
			// 重复闹钟 - 找到下一个匹配的日期
			const currentDay = now.getDay();
			let nextAlarmDate = new Date(now);
			
			// 今天是否在重复日期中
			if (alarm.repeatDays.includes(currentDay)) {
				const todayAlarmTime = new Date(now);
				todayAlarmTime.setHours(hours, minutes, 0, 0);
				
				if (todayAlarmTime > now) {
					// 今天的闹钟时间还没到
					return todayAlarmTime;
				}
			}
			
			// 找下一个重复日期
			for (let i = 1; i <= 7; i++) {
				const checkDate = new Date(now);
				checkDate.setDate(now.getDate() + i);
				const checkDay = checkDate.getDay();
				
				if (alarm.repeatDays.includes(checkDay)) {
					checkDate.setHours(hours, minutes, 0, 0);
					return checkDate;
				}
			}
		}
		
		return null;
	}
	
	// 取消本地通知
	cancelLocalNotification(alarmId) {
		// #ifdef APP-PLUS
		try {
			// 注意：plus.push.clear() 会清除所有通知
			// 这里我们只能清除所有通知，然后重新创建其他闹钟的通知
			plus.push.clear();
			console.log(`本地通知已取消: ${alarmId}`);
			return true;
		} catch (error) {
			console.error('取消本地通知失败:', error);
			return false;
		}
		// #endif
		
		return false;
	}
	
	// 重新创建所有活跃闹钟的通知
	recreateAllNotifications() {
		try {
			const alarms = uni.getStorageSync('alarms') || [];
			const activeAlarms = alarms.filter(alarm => alarm.isActive);
			
			// 清除所有现有通知
			// #ifdef APP-PLUS
			plus.push.clear();
			// #endif
			
			// 为每个活跃闹钟创建通知
			activeAlarms.forEach(alarm => {
				this.createLocalNotification(alarm);
			});
			
			console.log(`已重新创建 ${activeAlarms.length} 个闹钟通知`);
			return true;
			
		} catch (error) {
			console.error('重新创建通知失败:', error);
			return false;
		}
	}
	
	// 处理通知点击事件
	handleNotificationClick(message) {
		try {
			console.log('通知被点击:', message);
			
			const extra = message.payload || {};
			const alarmId = extra.alarmId;
			const alarmTime = extra.alarmTime;
			const alarmLabel = extra.alarmLabel;
			const vibrate = extra.vibrate;
			
			// 执行震动
			if (vibrate) {
				this.performVibration();
			}
			
			// 显示闹钟提醒
			uni.showModal({
				title: '⏰ 闹钟提醒',
				content: `${alarmTime} - ${alarmLabel}`,
				confirmText: '知道了',
				showCancel: false,
				success: () => {
					console.log('闹钟提醒已确认');
				}
			});
			
			// 如果是一次性闹钟，自动关闭
			if (alarmId) {
				const alarms = uni.getStorageSync('alarms') || [];
				const alarm = alarms.find(a => a.id === alarmId);
				if (alarm && alarm.type === 'once') {
					alarm.isActive = false;
					uni.setStorageSync('alarms', alarms);
				}
			}
			
		} catch (error) {
			console.error('处理通知点击失败:', error);
		}
	}
	
	// 执行震动
	performVibration() {
		let count = 0;
		const vibrate = () => {
			if (count < 5) {
				uni.vibrate({
					success: () => console.log(`震动 ${count + 1}`),
					fail: (err) => console.error('震动失败:', err)
				});
				count++;
				setTimeout(vibrate, 1000);
			}
		};
		vibrate();
	}
}

export default new LocalNotificationManager();